package com.yegs.jindie.serviceImpl;


import com.yegs.jindie.base.QuartzManager;
import com.yegs.jindie.entity.JobVo;
import com.yegs.jindie.entity.StoreException;
import com.yegs.jindie.repository.JobRepository;
import com.yegs.jindie.service.JobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class JobServiceImpl implements JobService {

    @Autowired
    private JobRepository jobRepository;


    @Override
    public List<JobVo> findAll() {
        List<JobVo>  list = jobRepository.findAll();
        return list;
    }

    @Override
    public void save(JobVo job) {
        jobRepository.save(job);
    }

    @Override
    public void triggerStatus(Long id,String states) {
        JobVo job = jobRepository.getOne(id);
        job.setStates(states);
        QuartzManager.addJob(job);
        jobRepository.save(job);
        jobRepository.flush();
    }

    @Override
    public void del(Long id) {
        jobRepository.deleteById(id);
    }

    @Override
    public void trigger(Long id) {
        JobVo job = jobRepository.getOne(id);
        if(job==null){
            throw new StoreException("ID错误!");
        }
        if("true".equals(job.getStates())){
            job.setStates("false");
            QuartzManager.removeJob(job);
        }else{
            job.setStates("true");
            QuartzManager.addJob(job);
        }
        jobRepository.save(job);
    }

    @Override
    public JobVo getJobByClassName(String jobClassName) {
        JobVo jobVo = null;
        List<JobVo> jobVos = jobRepository.findAll();
        for(JobVo job :jobVos){
            if(jobClassName.equals(job.getClassName())){
                jobVo = job;
            }
        }
        if(jobVo.getDate() == null){
            jobVo.setDate(new Date());
        }
        return jobVo;
    }



    //TODO把所有数据存在系统，减少与服务器交互。

}
